import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

// GET comments for a moment
export async function GET(req: NextRequest, { params }: { params: { momentId: string } }) {
  try {
    const { momentId } = params;
    // @ts-ignore
    const comments = await prisma.momentComment.findMany({
      where: { momentId },
      orderBy: { createdAt: 'asc' },
      include: {
        author: {
          select: {
            id: true,
            username: true,
            avatar: true,
          },
        },
      },
    });

    return NextResponse.json(comments);
  } catch (error) {
    console.error(`获取评论失败 (momentId: ${params.momentId}):`, error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}

// POST a new comment
export async function POST(req: NextRequest, { params }: { params: { momentId: string } }) {
  try {
    const authorId = getUserId(req);
    if (!authorId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { momentId } = params;
    const { content } = await req.json();

    if (!content || typeof content !== 'string' || content.trim().length === 0) {
      return NextResponse.json({ error: '评论内容不能为空' }, { status: 400 });
    }
    // @ts-ignore
    const newComment = await prisma.momentComment.create({
      data: {
        content: content.trim(),
        momentId,
        authorId,
      },
      include: {
        author: {
          select: {
            id: true,
            username: true,
            avatar: true,
          },
        },
      },
    });

    return NextResponse.json(newComment, { status: 201 });
  } catch (error) {
    console.error(`创建评论失败 (momentId: ${params.momentId}):`, error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 